import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import type { Variants } from 'framer-motion';
import axios from 'axios';
import BackButton from '../components/BackButton';

interface TransactionResult {
  trans_code: string;
  bank_date: string;
  resp_code: string;
  trans_sn: string;
  rrn: string;
  orderid: string;
  pan: string;
  balance: string | null;
  error_msg: string;
}

const CEP: React.FC = () => {
  const [formData, setFormData] = useState({
    pan: '',
    amount: '',
  });
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<TransactionResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  // 动画配置
  const containerVariants: Variants = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.6,
        ease: [0.43, 0.13, 0.23, 0.96]
      }
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const generateOrderId = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    return `TEST${year}${month}${day}${random}`;
  };

  const formatAmount = (amount: string): string => {
    // 移除非数字字符
    const numStr = amount.replace(/[^\d.]/g, '');
    // 转换为分（保留2位小数）
    const amountInCents = Math.round(parseFloat(numStr || '0') * 100);
    // 补齐11位
    return String(amountInCents).padStart(11, '0');
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 表单验证
    if (!formData.pan.trim()) {
      setError('请输入卡号');
      return;
    }
    if (!formData.amount.trim()) {
      setError('请输入交易金额');
      return;
    }

    setLoading(true);
    setError(null);
    setResult(null);

    try {
      // 构造请求数据
      const requestData = {
        pan: formData.pan.trim(),
        appid: '01',
        trans_amt: formatAmount(formData.amount),
        pay_order: generateOrderId(),
        merno: '999999999999997',
        terminal: '99999996'
      };

      console.log('发送请求数据:', requestData);

      const response = await axios.post('/api/cep', requestData);
      console.log('收到响应:', response.data);
      
      if (response.data.resp_code !== '0') {
        setError(response.data.error_msg || '交易失败');
      } else {
        setResult(response.data);
      }
    } catch (err: any) {
      console.error('请求错误:', err);
      const errorMessage = err.response?.data?.detail || err.response?.data?.error_msg || '交易失败，请稍后重试';
      setError(typeof errorMessage === 'string' ? errorMessage : '交易失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-[#eaf2ff] via-[#f0f7ff] to-[#f8fbff] py-12 px-4 sm:px-6 lg:px-8 relative overflow-hidden">
      <BackButton />
      
      {/* 背景装饰 */}
      <div className="fixed inset-0 -z-10 overflow-hidden">
        <div className="absolute -top-40 -left-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob"></div>
        <div className="absolute -bottom-40 -right-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob animation-delay-2000"></div>
      </div>

      <motion.div
        className="max-w-4xl mx-auto"
        initial="hidden"
        animate="visible"
        variants={containerVariants}
      >
        <div className="text-center mb-10">
          <h1 className="text-4xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-indigo-500 to-purple-500">
            消费交易
          </h1>
          <p className="mt-3 text-xl text-gray-600">
            输入卡号和金额进行消费交易测试
          </p>
        </div>

        <div className="bg-white/60 backdrop-blur-xl rounded-2xl p-8 shadow-[0_8px_32px_rgba(0,0,0,0.08)] border border-white/30">
          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label htmlFor="pan" className="block text-sm font-medium text-gray-700 mb-2">
                卡号
              </label>
              <input
                type="text"
                id="pan"
                name="pan"
                value={formData.pan}
                onChange={handleInputChange}
                className="w-full px-4 py-3 rounded-xl bg-white/50 border border-gray-200 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all duration-200 outline-none"
                placeholder="请输入卡号"
              />
            </div>
            
            <div>
              <label htmlFor="amount" className="block text-sm font-medium text-gray-700 mb-2">
                金额（元）
              </label>
              <input
                type="text"
                id="amount"
                name="amount"
                value={formData.amount}
                onChange={handleInputChange}
                className="w-full px-4 py-3 rounded-xl bg-white/50 border border-gray-200 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all duration-200 outline-none"
                placeholder="请输入交易金额"
              />
            </div>
            
            <div>
              <button
                type="submit"
                disabled={loading}
                className="w-full py-3 px-6 bg-gradient-to-r from-indigo-500 to-purple-500 text-white rounded-xl hover:shadow-lg hover:shadow-indigo-500/30 transition-all duration-200 disabled:opacity-50"
              >
                {loading ? '处理中...' : '提交交易'}
              </button>
            </div>

            {error && (
              <div className="p-4 rounded-xl bg-red-50 text-red-700 text-sm">
                {error}
              </div>
            )}

            <AnimatePresence>
              {result && (
                <motion.div
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  className="mt-8 space-y-4 bg-white/80 rounded-xl p-6"
                >
                  <div className="flex items-center justify-center mb-4">
                    <span className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-green-100">
                      <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                    </span>
                  </div>
                  <h3 className="text-xl font-semibold text-center text-gray-800 mb-4">交易成功</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-4">
                      <div>
                        <p className="text-sm text-gray-500">卡号</p>
                        <p className="text-base font-medium text-gray-900 font-mono">
                          {result.pan}
                        </p>
                      </div>
                      <div>
                        <p className="text-sm text-gray-500">交易流水号</p>
                        <p className="text-base font-medium text-gray-900 font-mono">
                          {result.trans_sn}
                        </p>
                      </div>
                    </div>
                    <div className="space-y-4">
                      <div>
                        <p className="text-sm text-gray-500">交易日期</p>
                        <p className="text-base font-medium text-gray-900">
                          {`${result.bank_date.slice(0, 4)}-${result.bank_date.slice(4, 6)}-${result.bank_date.slice(6, 8)}`}
                        </p>
                      </div>
                      <div>
                        <p className="text-sm text-gray-500">订单号</p>
                        <p className="text-base font-medium text-gray-900 font-mono">
                          {result.orderid}
                        </p>
                      </div>
                    </div>
                  </div>
                  {result.balance && (
                    <div className="mt-4 pt-4 border-t border-gray-100">
                      <div className="flex justify-between items-center">
                        <span className="text-sm text-gray-500">余额</span>
                        <span className="text-lg font-semibold text-indigo-600">
                          {parseFloat(result.balance) / 100} 元
                        </span>
                      </div>
                    </div>
                  )}
                </motion.div>
              )}
            </AnimatePresence>
          </form>
        </div>
      </motion.div>
    </div>
  );
};

export default CEP; 